import PubSub from 'pubsub-js';
import moment from 'moment'
import request from '../../../../utils/request'
import postRequest from '../../../../utils/postRequest'
// 获取全局实例
const appInstance = getApp();
const DB = wx.cloud.database();
const collectDB = DB.collection("collect");
const _ = DB.command;
let startX = 0; // 手指起始的坐标
let moveX = 0; // 手指移动的坐标
let moveDistance = 0; // 手指移动的距离
let tuodong = false;
const play_ = appInstance.globalData.backgroundAudioManager
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPlay: false, // 音乐是否播放
    playorder: '',  //控制播放顺序 icon-xunhuanbofang:循环播放 icon-suijibofang_ ：随机播放 icon-danquxunhuan1 ：单曲循环
    listHide: false,  //播放列表隐藏
    song: {}, // 歌曲详情对象
    musicId: '', // 音乐id
    musicLink: '', // 音乐的链接
    currentTime: '00:00',  // 实时时间
    durationTime: '00:00', // 总时长
    currentWidth: 0, // 实时进度条的宽度
    shoucang:false,     //收藏
    sortType:1,       //评论类型
    comments:[],        //评论列表
    TabCur: 0,
    pageNo:1,
    cursor:0,
    scrollLeft:0,
    // hotcommentsLength:0,   //热门评论长度
    commentsLength:0,    //推荐评论长度
    commentTabs:['推荐',"最热","最新"],
    type:'' ,         //通信id
    inputContent: '',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    let type = options.type;
    let musicId = options.musicId;
    let playorder = appInstance.globalData.playorder 
    let isPlay = appInstance.globalData.isMusicPlay 
    this.setData({
      musicId,
      type,
      playorder,
      isPlay
    })



    // 获取音乐详情
    this.getMusicInfo();
    if(appInstance.globalData.isMusicPlay && appInstance.globalData.musicId === musicId){ 
      // 修改当前页面音乐播放状态为true
      this.setData({
        isPlay: true
      })
    }
    // 监视音乐播放/暂停/停止
    play_.onPlay(() => {
      this.changePlayState(true);
      // console.log("播放")
      // 修改全局音乐播放的状态
      appInstance.globalData.musicId = musicId;
    });
    play_.onPause(() => {
      // console.log("暂停")
      this.changePlayState(false);
    });
    play_.onStop(() => {
      
      this.changePlayState(false);
    });
    
    // 监听音乐播放自然结束
    play_.onEnded(() => {
      let {playorder} = this.data
      switch(playorder) {
        case 'icon-danquxunhuan1':
           break;
        case 'icon-suijibofang_':
          appInstance.globalData.currentIndex = Math.round(Math.random()*appInstance.globalData.playList.length);
          break;
        default:     
          if(appInstance.globalData.currentIndex === appInstance.globalData.playList.length - 1){
            appInstance.globalData.currentIndex = -1;
          }
          appInstance.globalData.currentIndex++;
          
   }  

   this.getMusicInfo()

      // 将实时进度条的长度还原成 0；时间还原成 0；
      this.setData({
        currentWidth: 0,
        currentTime_nos:0,
        currentTime: '00:00'
      })
    });
    
    // 监听音乐实时播放的进度
    play_.onTimeUpdate(() => {
      // console.log('总时长: ', play_.duration);
      // console.log('实时的时长: ', play_.currentTime);
      // 格式化实时的播放时间
      let currentTime_nos
      currentTime_nos = play_.currentTime   
      let currentTime = moment(play_.currentTime * 1000).format('mm:ss')
      // console.log(play_.duration)
      let currentWidth = play_.currentTime/play_.duration * 450;
      if(!tuodong){
        this.setData({
          currentTime,
          currentTime_nos,
          currentWidth
        })
      }
    })
     
  
    
  },
 
  //获取音乐收藏状态
  DBstatus(){
    // console.log("shujuku")
    let musicId = this.data.musicId/1
    // console.log(typeof musicId)
    let that = this
    const _ = DB.command
    // console.log(_)
      collectDB.where(_.and([
        {
          userId: appInstance.globalData.userId
        },
        {
          likemusics: {
            id: musicId
          }
        }
      ]))
      .get({
        success: function(res) {
          console.log(res.data.length)
          if(res.data.length !== 0 ){
            console.log(res.data)
            that.setData({
              shoucang:true
            })
          }else{
            that.setData({
              shoucang:false
            })          
          }
        }
      })
  },




  // 修改播放状态的功能函数
  changePlayState(isPlay){
    // 修改音乐是否的状态
    this.setData({
      isPlay
    })
  
    // 修改全局音乐播放的状态
    appInstance.globalData.isMusicPlay = isPlay;
  },








  // 获取音乐详情的功能函数
  async getMusicInfo(){
    // console.log(musicId)
    let musicId = appInstance.globalData.playList[appInstance.globalData.currentIndex].id
    let songData = await request('/song/detail', {ids: musicId});
    // console.log(songData)
    // songData.songs[0].dt 单位ms
    let durationTime = moment(songData.songs[0].dt).format('mm:ss');
    this.setData({
      song: songData.songs[0],
      durationTime,
      musicId,
      pageNo:1,
      cursor:0
    })
    
    
    // 动态修改窗口标题
    wx.setNavigationBarTitle({
      title: this.data.song.name
    })

    //播放音乐
   
    this.getMusicUrl(musicId)
    appInstance.globalData.songData = songData
    this.getconnment(musicId)

  },

  // 获取音乐评论
  async getconnment(musicId){
      let {comments,sortType,pageNo,cursor} = this.data
      let id = musicId
      let pageSize = 40
      if(sortType==1){
         pageSize = 200
      }
      console.log(id,"+",sortType,"+",pageNo)
      let res = await request("/comment/new",{type:0,id,pageSize,sortType,pageNo,cursor})
      if(res.code==200&&res.comments!==[]){
        console.log(res)
        pageNo++
        comments.push(...res.data.comments)
        // console.log(res.data.cursor/1)
      
        this.setData({
          comments,
          cursor:res.data.cursor/1,
          pageNo
        })
      }

  },

  // 点击切换音乐评论
  tabSelect(e) {
    let {sortType,musicId} = this.data
    if(this.data.TabCur == e.currentTarget.dataset.id){
      return 
    }else{
      sortType=e.currentTarget.dataset.id+1
      let cursor = 0
      this.setData({
        sortType,
        pageNo:1,
        cursor,
        comments:[],
        TabCur: e.currentTarget.dataset.id,
        scrollLeft: (e.currentTarget.dataset.id-1)*60
      })
    }
    this.getconnment(musicId)
  },

  chudi(){
    let {musicId} = this.data
    // console.log(TabCur)
    this.getconnment(musicId)
  },

  //输入评论
  // handleInputChange(event){
  //     this.setData({
  //       inputContent: event.detail.value.trim(),
  //     })
  // },
  handleInputChange(e) {
    this.setData({
      inputContent:e.detail.value
    })
  },
  //发送评论
  async sendcomment(){
    
    let {inputContent,musicId} = this.data
    let res = await postRequest("/comment",{id:musicId,content:inputContent,t:1,type:0})
    
    if(res.code == 200){
      wx.showToast({
        title: '上传成功!',
        duration: 1000,
        icon:"success",
        success:()=>{
        }
      })
      this.setData({
        inputContent:''
      })
    }
  },







  // 点击播放/暂停的回调
  handleMusicPlay(){
    let isPlay = !this.data.isPlay;
    
    let {musicId, musicLink} = this.data;
    this.musicControl(isPlay, musicId, musicLink);
  },
  





  // 控制音乐播放/暂停的功能函数
   musicControl(isPlay, musicId, musicLink){
    
    if(isPlay){ // 音乐播放
      play_.play();
    }else { // 暂停音乐
      play_.pause();
    }
    
  },


  // 获取音乐url
 async getMusicUrl(musicId){
   
   let {musicLink} = this.data
  
    // 获取音乐播放链接
    let musicLinkData = await request('/song/url', {id: musicId});

    musicLink = musicLinkData.data[0].url;
    
    this.setData({
      musicLink
    })
     this.flag = true;
    // 返回url为空 自动播放下一首
    if(!this.data.musicLink &&  this.flag === true){
      this.flag = false;
     
        wx.showToast({
          title: '该单曲已下架!',
          duration: 2000,
          image:'/static/images/sorry.png',
          success:()=>{
          }

        })

        if(appInstance.globalData.currentIndex === appInstance.globalData.playList.length - 1){
          appInstance.globalData.currentIndex = -1;
        }
        appInstance.globalData.currentIndex++;
        // PubSub.publish(this.data.type, 'next')
        // 将实时进度条的长度还原成 0；时间还原成 0；
        this.setData({
          currentWidth: 0,
          currentTime: '00:00'
        })
        this.getMusicInfo();
        //获取音乐url
        // this.getMusicUrl(musicId);
        // 自动播放当前的音乐
        this.musicControl(true, this.data.musicId,this.data.musicLink);
       return 
      }
      wx.removeStorageSync({
        key: 'songInfo',
      })
      wx.setStorageSync(
        'songInfo',
         JSON.stringify({
          id:this.data.song.id,
          type:this.data.type,
          songname:this.data.song.al.name,
          arname:this.data.song.ar[0].name,
          picurl:this.data.song.al.picUrl,
          musicLink:this.data.musicLink
        }),
  
      )
      
      appInstance.globalData.songInfo = {
        id:this.data.song.id,
        type:this.data.type,
        songname:this.data.song.al.name,
        arname:this.data.song.ar[0].name,
        picurl:this.data.song.al.picUrl,
        musicLink:this.data.musicLink
      }
      // console.log(appInstance.globalData.songInfo)
      

  play_.src = musicLink;
  play_.title = this.data.song.name;
  this.DBstatus()
 },



  
  // 点击切歌的回调
  handleSwitch(event){
    let {playorder} = this.data
    // 获取切歌的类型
    let type = event.currentTarget.id;
    if(playorder==='icon-suijibofang_'){
      appInstance.globalData.currentIndex = Math.round(Math.random()*appInstance.globalData.playList.length);
      // console.log(appInstance.globalData.currentIndex)
    }else{
      if(type === "next"){
        if(appInstance.globalData.currentIndex === appInstance.globalData.playList.length - 1){
          appInstance.globalData.currentIndex = -1;
        }
        appInstance.globalData.currentIndex++;
      }else{
        if(appInstance.globalData.currentIndex === 0){
          appInstance.globalData.currentIndex = appInstance.globalData.playList.length 
        }
        appInstance.globalData.currentIndex--;
      }
    }


    // 关闭当前播放的音乐
    play_.stop();
          // 获取音乐详情信息
          this.getMusicInfo();
          //获取音乐url
          // this.getMusicUrl(musicId);
          // 自动播放当前的音乐
          this.musicControl(true, this.data.musicId,this.data.musicLink);
    // 发布消息数据给recommendSong页面
    // console.log(appInstance.globalData.currentIndex)
    // PubSub.publish(this.data.type, type)
    //刷新url
    // this.flashurl();
  },

  //显示播放列表
  playlistshow(){
    let listHide = !this.data.listHide
    this.setData({
      listHide
    })
  },
  //隐藏播放列表
  playlisthide(){

    let listHide = !this.data.listHide
    if(!listHide === false)return
    else{
      this.setData({
        listHide
      })
    }
  },


  //点击音乐列表
  changePlay(event) {
    // console.log(event.detail.musicId)
    let musicid = event.detail.musicId
    let musicindex = event.detail.musicindex
    appInstance.globalData.currentIndex = musicindex
    this.getMusicInfo(musicid)
    if(appInstance.globalData.isMusicPlay && appInstance.globalData.musicId === musicid){ 
      // 修改当前页面音乐播放状态为true
      this.setData({
        isPlay: true,
      })
    }
    this.setData({
      listHide: false
    })
  },

  //切换播放顺序
  handleSwitchplayorder(){
    let {playorder} = this.data
    
    switch(playorder) {
      case 'icon-xunhuanbofang':
         playorder = 'icon-suijibofang_';
         appInstance.globalData.playorder = playorder
         break;
      case 'icon-suijibofang_':
        playorder = 'icon-danquxunhuan1';
        appInstance.globalData.playorder = playorder;
         break;
      case 'icon-danquxunhuan1':
         playorder = 'icon-xunhuanbofang';
         appInstance.globalData.playorder = playorder;
          break;
    } 
    this.setData({
      playorder
    })
  },

  //抽屉
showModal(e) {
  this.setData({
    modalName: e.currentTarget.dataset.target
  })
},
hideModal(e) {
  this.setData({
    modalName: null
  })
},


 shoucang(){
  // console.log("shujuku")
  // let musicId = this.data.musicId/1
  let {shoucang} = this.data
  let {song} = this.data
  let inserlist = {
    id:song.id/1,
    name:song.name,
    url:song.al.picUrl,
    ar:song.al
  }
  let that = this
  if(!shoucang){
    collectDB.where({userId:appInstance.globalData.userId}).get({
     success(res){
       if(res.data.length === 0){  
       }else{
         collectDB.where({userId:appInstance.globalData.userId}).update({
           data:{
             likemusics: _.unshift(inserlist)
           },
           success: function(res) {
             if(res.stats.updated===1){
               console.log("添加成功：",res)
               that.setData({
                 shoucang:true
               })
             }
           },
           false(err){
             console.log("添加失败",err)
           }
         })
         
       }
      
     }
   })
  }else{
      console.log("取消收藏")
      collectDB.where({userId:appInstance.globalData.userId}).get({
        success(res){
          if(res.data.length === 0){  return
          }else{
            console.log("用户存在")
            collectDB.where({userId:appInstance.globalData.userId}).update({
              data:{
                likemusics: _.pull(inserlist)
              },
              success: function(res) {
                if(res.stats.updated===1){
                  console.log("添加成功：",res)
                  that.setData({
                    shoucang:false
                  })
                }
              },
              false(err){return
              }
            })
            
          }
         
        }
      })
  }
},

// 评论点赞
async dianzan2(event){
  let dataset = event.currentTarget.dataset
  let commtype = dataset.commtype
  if(commtype==='comments'){
    let {comments} = this.data
    let liked = comments.liked
    let t = ''
    if(comments[dataset.cindex].t){
      t = (comments[dataset.cindex].t==1)?0:1
    }else{
       t = comments[dataset.cindex].liked?0:1
    }
    let res = await request("/comment/like",{id:this.data.musicId,type:0,cid:dataset.cid,t})
    if(res.code=200){
      if(t==1){
        comments[dataset.cindex].likedCount++
      }else{
        comments[dataset.cindex].likedCount--
      }
      comments[dataset.cindex].liked=(t==1)?true:false
      comments[dataset.cindex].t = t
      this.setData({
        comments
      })
    }else if(res.code==301){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        success: () => {
          // 跳转至登录界面
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
      })
    }
  }else{
    let {comments} = this.data
    let liked = comments.liked
    let t = ''
    if(comments[dataset.cindex].t){
      t = (comments[dataset.cindex].t==1)?0:1
    }else{
       t = comments[dataset.cindex].liked?0:1
    }
    let res = await request("/comment/like",{id:this.data.musicId,type:0,cid:dataset.cid,t})
    if(res.code=200){
      if(t==1){
        comments[dataset.cindex].likedCount++
      }else{
        comments[dataset.cindex].likedCount--
      }
      comments[dataset.cindex].liked=(t==1)?true:false
      comments[dataset.cindex].t = t
      this.setData({
        comments
      })
    }else if(res.code==301){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        success: () => {
          // 跳转至登录界面
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
      })
    }
  }

},
handleTouchStart(event){
  // console.log(event)
  
  startX = event.touches[0].clientX;
  console.log(startX)
},
handleTouchMove(event){
  tuodong = true
  // console.log(event)
  // event.stopPropagation()
  let { currentTime_nos } = this.data
  // console.log("currentTime_nos",currentTime_nos)
  moveX = event.touches[0].clientX;
  // console.log("moveX:",moveX)
  moveDistance = moveX - startX ;
  let currentWidth = 0
  // console.log("moveDistance:",moveDistance)
  if((currentTime_nos + moveDistance)/play_.duration>=1){
    currentWidth = 450
  }else{
    currentWidth = (currentTime_nos + moveDistance)/play_.duration * 450
  }
 
 this.setData({
  currentWidth
 })
//  console.log("currentWidth:",currentWidth)

//  console.log("_____________________________________________________________________")

},

handleTouchEnd(){
  tuodong = false
  let { currentTime_nos } = this.data
  console.log("currentTime_nos:",currentTime_nos)
  console.log("moveDistance:",moveDistance)
  let sendtime = 0
  if((currentTime_nos + moveDistance)/play_.duration >= 1){
    sendtime = play_.duration - 2
  }else{
    sendtime = currentTime_nos + moveDistance
  }
   

  // console.log(sendtime)
  play_.seek(sendtime)

  
  
  // console.log("手指离开")
},


downmusic(){
  let musicName = this.data.song.name
  let artname = this.data.song.ar[0].name
  let that = this
  let dawnlownUrl = wx.env.USER_DATA_PATH+"/"+ musicName+"-"+ artname + ".mp3"
  wx.getSavedFileList({  // 获取文件列表
    success(res) {
      console.log('扫描数据成功！',res)
    }
  })
  wx.showLoading({
    title: '缓存中',
    duration:2000
})

    
    const  downloadTask =  wx.downloadFile({
          url:this.data.musicLink, 
          success:function(res){
            // console.log(res);
            if(res.errMsg !== 'downloadFile:ok'){
              console.log("缓存加入失败重新加载！",res)
              // that.downmusic()
            }else{

            }
            var rr=res.tempFilePath;
            // console.log(rr)
            const FileSystemManager =  wx.getFileSystemManager()
            FileSystemManager.saveFile({
              tempFilePath:rr,
              filePath:dawnlownUrl,
              success(suss){
                console.log("缓存成功：",suss)
                if(suss.errMsg !== 'saveFile:ok'){
                  console.log("内存加入失败重新加载！759",suss)
                  // that.downmusic()
                }else{
                  console.log("内存加入成功！")
                  downloadTask.abort() // 取消下载任务
                  return
                }
              },
              fail(err){
                console.log("内存加入失败重新加载！768",err)
              }
            })
          },
          fail(err){
            console.log("缓存写入失败",err)
             downloadTask.abort() // 取消下载任务
             that.downmusic()
          }  
          })
        
        downloadTask.onProgressUpdate((res) => {
        if(res.progress%10 == 0){
          console.log('下载进度', res.progress)
        }
          // console.log('已经下载的数据长度', res.totalBytesWritten)
          // console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite)
          if(res.totalBytesWritten==res.totalBytesExpectedToWrite){
            console.log("下载完成")
            downloadTask.abort() // 取消下载任务
          }
        })
},








































  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
